package com.boyu.backend;

import com.boyu.common.BaseController;
import com.boyu.common.ColumnLogic;
import com.boyu.common.SystemConst;
import com.boyu.common.model.Article;
import com.boyu.common.model.Product;
import com.boyu.common.model.ProductAttr;
import com.boyu.common.showmodel.ShowColumn;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import org.joda.time.DateTime;

import java.util.List;

/**
 * IndexController
 */
public class _ArticleController extends BaseController {
    public static final String ARTICLE_LIST = "articleList";
    public static final String ARTICLE = "article";

    public void index() {
        List<ShowColumn> showColumns = ColumnLogic.getInstance().columnLoad();
        setSessionAttr(SystemConst.ADMIN_COLUMN, showColumns);
        Long columnId = getParaToLong(COLUMN_ID);

        String sqlEnd = " from t_article order by createTime desc";
        if (columnId != null) {
            sqlEnd = " from t_article where columnId ="+columnId+" order by createTime desc";
        }
        String para = getPara(0);
        Integer pageNum = 1;
        if (!para.equals("index")) {
            pageNum = Integer.parseInt(para);
        }
        Page<Article> articlePage = Article.dao.paginate(pageNum,8,"select id,title,createTime,columnId", sqlEnd);
        setAttr("articlePage",articlePage);
        setAttr(COLUMN_ID, columnId);
        render(INDEX_HTML);
    }

    public void add() {
        Long columnId = getParaToLong(COLUMN_ID);
        setAttr(COLUMN_ID, columnId);
        render(ADD_HTML);
    }

    public void edit() {
        long id = getParaToLong(ID);
        Article byId = Article.dao.findById(id);
        setAttr(ARTICLE, byId);
        setAttr(COLUMN_ID, byId.getColumnId());
        render(EDIT_HTML);
    }

    public void save() {
        UploadFile fileName = getFile("newImg", SystemConst.UPLOAD_ARTICLE);
        Article model = getModel(Article.class, "");
        if (fileName != null) {
            model.setImg(fileName.getFileName());
        }
        if (model.getId() != null) {
            model.update();
        } else {
            model.setCreateTime(DateTime.now().toDate());
            model.save();
        }
        String toUrl = String.format("%s?%s=%s", INDEX, COLUMN_ID, model.getColumnId());
        redirect(toUrl);
        //redirect(INDEX+"?columnId="+model.getColumnId());
    }
    public void del() {
        long id = getParaToLong(ID);
        Article.dao.deleteById(id);
        render(INDEX_HTML);
    }
}





